package com.ltv.xiangqibook.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.ltv.xiangqibook.common.XiangQiBookConfiguration;
import com.ltv.xiangqibook.model.Game;
import com.ltv.xiangqibook.model.Post;


public class XiangQiGameServlet extends HttpServlet {
    private static final Logger logger = LogManager.getLogger(XiangQiGameServlet.class);
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        
        String gameId = request.getParameter("game_id");
        
        if (gameId == null) {
        	gameId = (String) request.getSession(true).getAttribute("game_id");
        }
        
        if (gameId == null) {
        	return;
        }
        
        HttpSession session = request.getSession(true);
        session.setAttribute("game_id", gameId);

        //String moveList = "";
        //String comment = "";
        
        Game game = new Game();

        // connecting to database
        Connection con = null;  
        Statement stmt = null;
        ResultSet rs = null;
        
        Statement postStmt = null;
        ResultSet postRs = null;
        List<Post> posts = new ArrayList<Post>();
        try {
            con = ConnectionPool.getInstance().getConnection();
            stmt = con.createStatement();
            rs = stmt.executeQuery("SELECT * FROM games where game_id='" + gameId + "'");
            
            if (rs.next()) {
                game.setGameId((String) rs.getObject(1));
                game.setMoveList((String) rs.getObject(2));
                game.setStartIndex((Integer) rs.getObject(3));
                game.setComment((String) rs.getObject(4));
                game.setGameUrl((String) rs.getObject(5));
            }
            
            postStmt = con.createStatement();;
            postRs = postStmt.executeQuery("SELECT * FROM posts where game_id='" + gameId + "'");
            
            while (postRs.next()) {
                Post post = new Post();
                post.setGameId(postRs.getString(2));
                post.setSenderName(postRs.getString(3));
                post.setComment(postRs.getString(4));
                posts.add(post);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                if(rs != null) {
                    rs.close();
                    rs = null;
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            try {
                if(postRs != null) {
                    postRs.close();
                    postRs = null;
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            try {
                if(stmt != null) {
                    stmt.close();
                    stmt = null;
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            try {
                if(postStmt != null) {
                	postStmt.close();
                	postStmt = null;
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            try {
                if(con != null) {
                    ConnectionPool.getInstance().returnConnection(con);
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        }
        String boardSize = request.getParameter("boardSize");
        
        if (boardSize != null) {
        	request.getSession(true).setAttribute("boardSize", boardSize);
        } else {
        	boardSize = (String) request.getSession(true).getAttribute("boardSize");
        	if (boardSize == null) {
            	boardSize = "medium";
            }
        }
        

        String embedGame = "";
        
        if (boardSize.equalsIgnoreCase("small")) {
        	embedGame = "<script src=\"http://www.java.com/js/deployJava.js\"></script>\n" +
            		"<script>\n" +
            		"var attributes = { code:'com.ltv.xiangqiplugin.views.ChessApp.class', archive:'xiangqiplugin.jar',  width:400, height:350} ;\n" +
            		"var parameters = {jnlp_href: 'views/xiangqiplugin_"
            			+ XiangQiBookConfiguration.getInstance().getPluginVersion() + ".jnlp', moveList: '" + game.getMoveList() + "', " +
            			"boardSize: 'small', " +
            			"startIndex: '" + game.getStartIndex() + "'" + "} ;\n" +
            		"deployJava.runApplet(attributes, parameters, '1.4');\n" +
            		"</script>";
        } else if (boardSize.equalsIgnoreCase("medium")) {
        	embedGame = "<script src=\"http://www.java.com/js/deployJava.js\"></script>\n" +
            		"<script>\n" +
            		"var attributes = { code:'com.ltv.xiangqiplugin.views.ChessApp.class', archive:'xiangqiplugin.jar',  width:550, height:500} ;\n" +
            		"var parameters = {jnlp_href: 'views/xiangqiplugin_"
            			+ XiangQiBookConfiguration.getInstance().getPluginVersion() + ".jnlp', moveList: '" + game.getMoveList() + "', " +
            			"boardSize: 'medium', " +
            			"startIndex: '" + game.getStartIndex() + "'" + "} ;\n" +
            		"deployJava.runApplet(attributes, parameters, '1.4');\n" +
            		"</script>";
        } else if (boardSize.equalsIgnoreCase("large")) {
        	embedGame = "<script src=\"http://www.java.com/js/deployJava.js\"></script>\n" +
            		"<script>\n" +
            		"var attributes = { code:'com.ltv.xiangqiplugin.views.ChessApp.class', archive:'xiangqiplugin.jar',  width:700, height:650} ;\n" +
            		"var parameters = {jnlp_href: 'views/xiangqiplugin_"
            			+ XiangQiBookConfiguration.getInstance().getPluginVersion() + ".jnlp', moveList: '" + game.getMoveList() + "', " +
            			"boardSize: 'large', " +
            			"startIndex: '" + game.getStartIndex() + "'" + "} ;\n" +
            		"deployJava.runApplet(attributes, parameters, '1.4');\n" +
            		"</script>";
        }
        
        PrintWriter out = response.getWriter();
        
        String yourName = request.getParameter("sender_name");
        String yourComment = request.getParameter("comment");
        
        if (yourName == null) yourName = "";
        if (yourComment == null) yourComment = "";
        
        out.println(
                        "<HTML>\n" +
                        "<HEAD>\n" +
                        "<link rel=\"stylesheet\" type=\"text/css\" href=\"css/xiangqibook.css\" />" +
                        "</HEAD>" +
                        "<BODY>\n" +
                        "<table>\n" +
                        "<tr>\n"
                        );
        out.println("<td valign=\"top\">\n");
        
        String checkSmall = "", checkMedium = "", checkLarge = "";
        if (boardSize.equalsIgnoreCase("small")) {
        	checkSmall = "checked";
        } else if (boardSize.equalsIgnoreCase("medium")) {
        	checkMedium = "checked";
        } else if (boardSize.equalsIgnoreCase("large")) {
        	checkLarge = "checked";
        }
        
        out.println("<FORM action=\"XiangQiGame\">\n");
        out.println("<input type=\"radio\" name=\"boardSize\" value=\"small\" " + checkSmall + " onclick=\"changeBoardSize(0)\">Small\n");
        out.println("<input type=\"radio\" name=\"boardSize\" value=\"medium\" " + checkMedium + " onclick=\"changeBoardSize(1)\">Medium\n");
        out.println("<input type=\"radio\" name=\"boardSize\" value=\"large\" " + checkLarge + " onclick=\"changeBoardSize(2)\">Large\n");
        out.println("</FORM>\n");
        
        out.println(embedGame + "</td>" + "\n" +
                        "<td valign=\"top\"><br><br>" + newLineToBreak(game.getComment()) + "</td>" + "\n" +
                        "</tr>\n" +
                        "</table>\n"
                );
        
        out.println("<h2>Comments</h2>\n");
        out.println("<hr>\n");
        
        out.println("<table class=\"list\" width=\"100%\">\n");
        boolean odd = true;
        for (Post post : posts) {
            if (odd) {
                out.println("<tr class=\"odd\"><td>");
                out.println("<p>\n");
                out.println("<code>" + post.getSenderName() + "</code>\n");
                out.println("</p>\n");
                out.println("<p>" + newLineToBreak(post.getComment()) + "</p>");
                out.println("</td></tr>");
            } else {
                out.println("<tr class=\"even\"><td>");
                out.println("<p>\n");
                out.println("<code>" + post.getSenderName() + "</code>\n");
                out.println("</p>\n");
                out.println("<p>" + newLineToBreak(post.getComment()) + "</p>");
                out.println("</td></tr>");
            }
            odd = !odd;
        }
        out.println("</table>\n");
        
        out.println("<script>\n");
        out.println("    function validateForm() {\n");
        out.println("        document.getElementById('sender_error_msg').innerHTML = '';\n");
        out.println("        document.getElementById('comment_error_msg').innerHTML = '';\n");
        out.println("        var ret = true;\n");
        out.println("        var senderName = document.forms[\"postForm\"][\"sender_name\"].value;\n");
        out.println("        if (senderName == null || senderName == \"\") {\n");
        out.println("            document.getElementById('sender_error_msg').innerHTML = '<font color=\"red\">Your name is required</font>';\n");
        out.println("            ret = false;\n");
        out.println("        }\n");

        out.println("        var comment = document.forms[\"postForm\"][\"comment\"].value;\n");
        out.println("        if (comment == null || comment == \"\") {\n");
        out.println("            document.getElementById('comment_error_msg').innerHTML = '<font color=\"red\">Your comment is required</font>';\n");
        out.println("            ret = false;\n");
        out.println("        }\n");
                
        out.println("        return ret;\n");
        out.println("    }\n");
        
        out.println("</script>\n");

        out.println("<form name=\"postForm\" action=\"XiangQiPost\" onsubmit=\"return validateForm()\">\n");

        out.println("<table width=\"100%\">\n");
        
        out.println("<tr>\n");
        out.println("<td><input type=\"hidden\" name=\"game_id\" value=\"" + gameId + "\"/><br></td>\n");
        out.println("</tr>\n");
        
        out.println("<tr>\n");
        out.println("<td></td>\n");
        out.println("<td><div id=\"sender_error_msg\"></div></td>\n");
        out.println("</tr>\n");

        out.println("<tr>\n");
        out.println("<td width=\"15%\"><span>Your Name</span></td>\n");
        out.println("<td width=\"85%\"><input style=\"width:100%\" type=\"text\" name=\"sender_name\" value=\"" + yourName + "\"/><br></td>\n");
        out.println("</tr>\n");
        
        out.println("<tr>\n");
        out.println("<td></td>\n");
        out.println("<td><div id=\"comment_error_msg\"></div></td>\n");
        out.println("</tr>\n");

        out.println("<tr>\n");
        out.println("<td><span>Your Comment</span></td>\n");
        out.println("<td><textarea style=\"width:100%\" name=\"comment\" rows=\"10\">" + breakToNewLine(yourComment) + "</textarea><br></td>\n");
        out.println("</tr>\n");
        
        out.println("<tr>\n");
        out.println("<td></td>\n");
        out.println("<td><iframe frameborder=\"0\" name=\"captcha_image\" src=\"XiangQiBookCaptcha\"></iframe></td>\n");
        out.println("</tr>\n");
        
        out.println("<tr>\n");
        out.println("<td>Enter above code<br></td>\n");
        out.println("<td><input style=\"width:50%\" type=\"text\" name=\"input_captcha\"/>" +
                "<a href=\"XiangQiBookCaptcha\" target=\"captcha_image\">Refresh</a><br></td>\n");
        out.println("</tr>\n");
        
        out.println("<tr>\n");
        out.println("<td><input type=\"submit\" value=\"Post Your Comment\"/><br></td>\n");
        out.println("</tr>\n");

        out.println("</table>\n");

        out.println("</form>\n");
        
        out.println("<script>\n");
        
        if (boardSize.equalsIgnoreCase("small")) {
        	out.println("    var myOption = 0;\n");
        } else if (boardSize.equalsIgnoreCase("medium")) {
        	out.println("    var myOption = 1;\n");
        } else if (boardSize.equalsIgnoreCase("large")) {
        	out.println("    var myOption = 2;\n");
        }
        
        out.println("    function changeBoardSize(i) {\n");
        out.println("        if (myOption != i) {\n");
        out.println("            myOption = i;\n");
        out.println("            var boardSize = document.forms[0].boardSize[i].value;\n");
        out.println("            document.forms[0].submit();\n");
        out.println("        }\n");
        out.println("    }\n");
        out.println("</script>\n");
        
        out.println("</BODY>\n" + "</HTML>");
        
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
    
    private String newLineToBreak(String str) {
        String ret = "";
        String arr[] = str.split("\n");
        for (int i = 0; i < arr.length - 1; i++) {
            ret += arr[i] + "<br>";
        }
        if (arr.length > 0) {
        	ret += arr[arr.length - 1];
        }
        
        return ret;
    }
    
    private String breakToNewLine(String str) {
        String ret = "";
        String arr[] = str.split("<br>");
        for (int i = 0; i < arr.length - 1; i++) {
            ret += arr[i] + "\n";
        }
        if (arr.length > 0) {
        	ret += arr[arr.length - 1];
        }
        	
        return ret;
    }

}
